package com.gan.springcloud.cloudgateway.config;


//import com.alibaba.csp.sentinel.adapter.gateway.common.rule.*;
//import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
//import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.*;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Configuration
public class GatewayConf {


    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        // 当访问到 http://127.0.0.1:8000/vip 直接跳转到唯品会的首页
        return builder.routes()
                .route(r -> r.path("/vip")
                        .uri("https://www.vip.com/").id("vip_route")
                ).build();
    }


    /*private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;
    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    public GatewayConf() {
    }*/

    /**
     * 配置SentinelGatewayBlockExceptionHandler，限流后异常处理
     * @return
     */
    //@Bean
    //@Order(Ordered.HIGHEST_PRECEDENCE)
    //public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
    //    return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    //}
    /**
     * 配置SentinelGatewayFilter
     * @return
     */
    /*@Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
    @PostConstruct
    public void doInit() {
        initGatewayRules();
    }*/
    /**
     * 配置限流规则
     */
    /*private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("cloud-account")
                .setCount(1) // 限流阈值
                .setIntervalSec(1) // 统计时间窗口，单位是秒，默认是 1 秒
        );
        GatewayRuleManager.loadRules(rules);
    }*/
}


